package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Aspect
@Component
public class AutoFillAspect {
    // 切入点设置
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}
    // 前置通知
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始进行数据填充");
       //获取方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法上的注解对象
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //获取数据库操作类型
        OperationType operationType = autoFill.value();
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        // 如果参数为空或长度为0，则直接返回，不进行数据填充
        if (args == null || args.length == 0){
            return;
        }
        // 获取第一个参数对象，通常为需要进行自动填充的实体对象
        Object object = args[0];
        //准备赋值的数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        //根据当前不同的操作类型，为对应的属性通过反射来赋值
        // 如果是INSERT操作,就修改创建时间、更新时间、创建人、更新人字段的值
        if (operationType == OperationType.INSERT)
        {
            Method setCreateTime = object.getClass().getMethod("setCreateTime", LocalDateTime.class);
            Method setUpdateTime = object.getClass().getMethod("setUpdateTime", LocalDateTime.class);
            Method setCreateUser = object.getClass().getMethod("setCreateUser", Long.class);
            Method setUpdateUser = object.getClass().getMethod("setUpdateUser", Long.class);

            setCreateTime.invoke(object, now);
            setUpdateTime.invoke(object, now);
            setCreateUser.invoke(object, currentId);
            setUpdateUser.invoke(object, currentId);
        }
        // 如果是UPDATE操作,就修改更新时间、更新人字段的值
        else if (operationType == OperationType.UPDATE)
        {
            Method setUpdateTime = object.getClass().getMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = object.getClass().getMethod("setUpdateUser", Long.class);

            setUpdateTime.invoke(object, now);
            setUpdateUser.invoke(object, currentId);
        }
        
    }
}
